<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\WorkMessage\Action\Dashboard;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Utils\Codec\Json;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\User\Logic\Traits\UserTrait;
use MoChat\App\WorkContact\Contract\WorkContactContract;
use MoChat\App\WorkEmployee\Contract\WorkEmployeeContract;
use MoChat\App\WorkMessage\Contract\WorkMessageContract;
use MoChat\App\WorkMessage\Logic\Traits\ContentTrait;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Request\ValidateSceneTrait;

/**
 * 群聊详情.
 * @Controller
 */
class RoomMessageIndex extends AbstractAction
{
    use ValidateSceneTrait;
    use ContentTrait;
    use UserTrait;

    /**
     * @var WorkMessageContract
     */
    protected $workMessageService;

    /**
     * @Inject
     * @var WorkEmployeeContract
     */
    protected $workEmployeeService;

    /**
     * @Inject
     * @var WorkContactContract
     */
    protected $contactService;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class)
     * })
     * @RequestMapping(path="/dashboard/workMessage/roomMessageIndex", methods="GET")
     */
    public function handle(): array
    {
        // 参数验证
        $this->validated($this->request->all());

        $this->workMessageService = make(WorkMessageContract::class, [$this->corpId()]);

        $wxRoomId = $this->request->input('wxRoomId');
        $page = $this->request->input('page');
        $perPage = $this->request->input('perPage');
        $content = $this->request->input('content');
        $startTime = $this->request->input('startTime');
        $endTime = $this->request->input('endTime');

        $options = [
            'page' => $page,
            'perPage' => $perPage,
            'orderByRaw' => 'id asc',
        ];

        $where = [
            ['wx_room_id', '=', $wxRoomId],
        ];

        if (! empty($content)) {
            $where[] = ['content', 'like', '%' . $content . '%'];
        }
        if (! empty($startTime) && ! empty($endTime)) {
            $where[] = ['msg_time', '>=', strtotime($startTime) * 1000];
            $where[] = ['msg_time', '<=', strtotime($endTime) * 1000];
        }

        $roomMessage = $this->workMessageService->getWorkMessageList($where, ['*'], $options);
        if (empty($roomMessage)) {
            return [];
        }

        $data = [];
        foreach ($roomMessage['data'] as $k => $v) {
            $otherData = $this->otherResData($v['from']);
            $msgContent = $this->contentFormat(Json::decode($v['content']), $v['msgType']);
            $type = $msgContent['type'];
            unset($msgContent['type']);
            $data[$k] = [
                'show' => $otherData['show'],
                'msgTime' => date('Y-m-d H:i:s', (int) ($v['msgTime'] * 0.001)),
                'type' => $type,
                'content' => $msgContent,
                'userInfo' => ['avatar' => $otherData['avatar'], 'nickname' => $otherData['name']],
            ];
        }

        return [
            'page' => [
                'perPage' => $roomMessage['per_page'],
                'total' => $roomMessage['total'],
                'totalPage' => $roomMessage['last_page'],
            ],
            'list' => $data,
        ];
    }

    /**
     * 验证规则.
     */
    protected function rules(): array
    {
        return [
            'wxRoomId' => 'required',
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
            'wxRoomId.required' => '群聊id 必填',
        ];
    }

    /**
     * 处理其它响应数据.
     * @param string $from ...
     * @return array ...
     */
    protected function otherResData(string $from): array
    {
        $data = [
            'name' => '系统',
            'avatar' => '',
            'isCurrentUser' => 0,
            'show' => 1,
        ];

        // 机器人
        if (strpos($from, 'we') === 0) {
            $data['name'] = '机器人';
        }

        // 客户
        //if (strpos($from, 'wo') === 0 || strpos($from, 'wm') === 0) {
        $contact = $this->contactService->getWorkContactByWxExternalUserId($from, ['id', 'name', 'avatar']);
        if (empty($contact)) { // 非客户
            // 员工
            $employee = $this->workEmployeeService->getWorkEmployeeByWxUserIdCorpIdWithTrashed($from, (int) user()['corpIds'][0], ['id', 'name', 'thumb_avatar']);
            if (!empty($employee)) {
                $data['show'] = 1;
                $data['name'] = $employee['name'];
                empty($employee['thumbAvatar']) || $data['avatar'] = file_full_url($employee['thumbAvatar']);
            }else{
                $data['name'] = $from;
                return $data;
            }

        }else{
            $data['show'] = 0;
            $data['name'] = $contact['name'];
            empty($contact['avatar']) || $data['avatar'] = file_full_url($contact['avatar']);
        }

        return $data;
    }
}
